package com.lujianfei.redpacketstat.ui.adapter

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.recyclerview.widget.AsyncListDiffer
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.lujianfei.redpacketstat.R
import com.lujianfei.redpacketstat.base.BaseAdapter
import com.lujianfei.redpacketstat.database.bean.UserEntity
import com.lujianfei.redpacketstat.databinding.AdapterItemHomeBinding
import com.lujianfei.redpacketstat.ui.viewmodel.MainViewModel
import com.lujianfei.redpacketstat.utils.Utils

class MainAdapter : BaseAdapter() {

    private var cardList = AsyncListDiffer<UserEntity>(this,DiffCallback())
    var mainViewModel : MainViewModel?= null

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        val dataBinding: ViewDataBinding = DataBindingUtil.inflate(LayoutInflater.from(parent.context), R.layout.adapter_item_home, parent, false)
        return MyViewHolder(dataBinding)
    }

    override fun getItemCount(): Int {
        return cardList.currentList.size
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        val userEntity = cardList.currentList[position]
        val viewHolder = holder as MyViewHolder
        val adapterItemHomeBinding = viewHolder.dataBinding as AdapterItemHomeBinding
        userEntity.statusString = Utils.getStatusString(userEntity.status)
        adapterItemHomeBinding.user = userEntity
        adapterItemHomeBinding.viewModel = mainViewModel
    }

    fun setData(cardList: MutableList<UserEntity>) {
        this.cardList.submitList(cardList)
    }

    class MyViewHolder : RecyclerView.ViewHolder {

        var dataBinding: ViewDataBinding?= null

        constructor(dataBinding: ViewDataBinding) : super(dataBinding.root) {
            this.dataBinding = dataBinding
        }
    }
}

class DiffCallback : DiffUtil.ItemCallback<UserEntity>() {
    override fun areItemsTheSame(oldItem: UserEntity, newItem: UserEntity): Boolean {
        return oldItem.id == newItem.id
    }

    override fun areContentsTheSame(oldItem: UserEntity, newItem: UserEntity): Boolean {
        return oldItem == newItem
    }

}